package com.example.chinesenation.Controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.chinesenation.Entity.Article;
import com.example.chinesenation.Entity.Policy;
import com.example.chinesenation.Entity.PolicyCollect;
import com.example.chinesenation.Entity.Resources;
import com.example.chinesenation.Exception.AuthenException;
import com.example.chinesenation.Redis.RedisService;
import com.example.chinesenation.Response.ResultType;
import com.example.chinesenation.Response.ServerResponse;
import com.example.chinesenation.Service.*;
import com.example.chinesenation.Utils.*;
import com.example.chinesenation.VO.MainPage.VOPolicyList;
import com.example.chinesenation.VO.PolicyPage.VOPolicyPage;
import com.example.chinesenation.VO.VOArticle;
import com.example.chinesenation.VO.VOPolicy;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author sakuraFallingDown
 * @version 1.0
 * @date 2021/1/18 16:22
 */
@Controller
@ResponseBody
@RequestMapping("/policy")
@CrossOrigin
public class PolicyController {


    private final Logger logger= LoggerFactory.getLogger(getClass());

    @Autowired
    private Audience audience;

    @Autowired
    private IBrowseRecordPolicyService browseRecordPolicyService;

    @Autowired
    private IPolicyListService policyListService;

    @Autowired
    private IPolicyCollectService policyCollectService;

    @Autowired
    private IResourcesService resourcesService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private RecommendedTools recommendedTools;

    /**
     * @param token 用户的token
     * @param id 文章的政策id
     * @param ip 用户浏览的ip ip用于做基数统计
     * @return 返回该id对应的政策信息
     */
    @ApiOperation("查看主键为ID的政策的具体信息")
    @RequestMapping("/{id}")//查看政策信息
    private ServerResponse<VOPolicy> getVoPolicy(@RequestHeader(value = "token", required = false) String token,
                                                 @PathVariable("id") String id,
                                                 @RequestHeader(value = "ip",required = false)String ip){
        if(token!=null&&!token.equals("")){
            String uid= JwtTokenUtil.getUserId(token,audience);
            if(!browseRecordPolicyService.savaRecord(uid,id)){
                logger.error("插入浏览记录失败uid:"+uid+",浏览政策id:"+id);
            }else{
                recommendedTools.ChangeUserInterestPolicyVectorByInterView(uid,id);
            }
        }
        VOPolicy voPolicy=new VOPolicy();
        if(redisService!=null&&redisService.hasComment(CommonURL.RedisPolicy+ id)){
            Object object=redisService.get(CommonURL.RedisPolicy+ id);
            if(object==null){
                return ServerResponse.createErrorsResponse(ResultType.NOTEXITS);
            }
            voPolicy=(VOPolicy)object;
            redisService.addPageView(CommonURL.RedisPolicyPageView+id,ip);//增加阅读量
            int pageView=redisService.getPageView(CommonURL.RedisPolicyPageView+id);
            voPolicy.setPageview(voPolicy.getPageview()+pageView);
            return ServerResponse.createSuccessResponse("查找政策信息成功",voPolicy);
        }
        Policy policy = policyListService.getById(id);
        if(policy==null){
            redisService.putMinute(CommonURL.RedisPolicy+ id,null,30);//设置半小时的空值缓存，防止缓存穿透
            throw new AuthenException(ResultType.NOTEXITS);
        }
        DataChanges.fromPolicyToVOPolicy(policy, voPolicy);
        if(voPolicy!=null) redisService.put(CommonURL.RedisPolicy+ id,voPolicy,24);//不为空，则永久存入redis
        redisService.addPageView(CommonURL.RedisPolicyPageView+id,ip);//增加阅读量，计数+1；
        voPolicy.setPageview(voPolicy.getPageview()+1);
        return ServerResponse.createSuccessResponse("查找政策信息成功",voPolicy);
    }

    @ApiOperation("收藏主键为id的政策接口")
    @PostMapping("/collect")//收藏某个id的政策
    private ServerResponse<String> CollectPolicy(@RequestHeader(value = "token", required = true) String token
            , @RequestParam(value = "id") String id){
        if(token!=null&&!token.equals("")){
            String uid= JwtTokenUtil.getUserId(token,audience);
            PolicyCollect pc=new PolicyCollect();
            pc.setPolicyId(id);
            pc.setUid(uid);
            if(policyCollectService.save(pc)){
                recommendedTools.ChangeUserInterestPolicyVectorByCollect(uid,id,true);
                return ServerResponse.createSuccessResponse("收藏成功",null);
            }else{
                return ServerResponse.createErrorsResponse(ResultType.ERROR);
            }
        }else{
            return ServerResponse.createErrorsResponse(ResultType.TOKENNULL);
        }
    }

    @ApiOperation("取消收藏主键为id的政策接口")
    @PostMapping("/dropcollect")//取消收藏某个id的政策，按照uid和政策id
    private ServerResponse<String> DropCollectPolicy(@RequestHeader(value = "token", required = true) String token
            , @RequestParam(value = "id") String id){
        if(token!=null&&!token.equals("")){
            String uid= JwtTokenUtil.getUserId(token,audience);
            QueryWrapper<PolicyCollect> qw=new QueryWrapper<>();
            qw.eq("uid",uid);
            qw.eq("policy_id",id);
            if(policyCollectService.remove(qw)){
                recommendedTools.ChangeUserInterestPolicyVectorByCollect(uid,id,false);
                return ServerResponse.createSuccessResponse("取消收藏成功",null);
            }else{
                return ServerResponse.createErrorsResponse(ResultType.ERROR);
            }
        }else{
            return ServerResponse.createErrorsResponse(ResultType.TOKENNULL);
        }
    }

    @ApiOperation("判断主键为id的政策是否被目标用户收藏过的接口")
    @PostMapping("/iscollect")//判断某个id的政策是否收藏过
    private ServerResponse<String> isCollectPolicy(@RequestHeader(value = "token", required = true) String token
            ,@RequestParam(value = "id") String id){
        if(token!=null&&!token.equals("")){
            String uid= JwtTokenUtil.getUserId(token,audience);
            QueryWrapper<PolicyCollect> qw=new QueryWrapper<>();
            qw.eq("uid",uid);
            qw.eq("policy_id",id);
            if(policyCollectService.getOne(qw)!=null){
                return ServerResponse.createSuccessResponse("true",null);
            }else{
                return ServerResponse.createSuccessResponse("false",null);
            }
        }else{
            return ServerResponse.createErrorsResponse(ResultType.TOKENNULL);
        }
    }

    @ApiOperation("政策主页面获取信息的接口")
    @PostMapping("/policy")//政策主页的信息
    private ServerResponse<VOPolicyPage> policy(@RequestHeader(value = "token", required = false) String token,
                                                @RequestParam(value = "current") int current,
                                                @RequestParam(value = "size") int size){
        VOPolicyPage voPolicyPage=new VOPolicyPage();
        List<Resources> resourceList=new ArrayList<>();//首页轮播图
        if(redisService!=null&&redisService.hasKey("policy:resources")){
            resourceList=(List<Resources>)redisService.get("policy:resources");
        }else {
            QueryWrapper<Resources> qw = new QueryWrapper<>();
            qw.likeRight("res_url", "政策轮播图");
            resourceList=resourcesService.list(qw);
            if(resourceList!=null&&resourceList.size()!=0){
                resourceList.forEach(resource->{
                    resource.setResUrl(CommonURL.imgUrl+resource.getResUrl());
                });
                redisService.put("policy:resources",resourceList);
            }
        }

        List<VOPolicyList> rankPolicyLists=(List<VOPolicyList>)redisService.get(CommonURL.MainPagePolicy);//今日热点政策，类似于Rank

        rankPolicyLists = MainController.getRankPolicy(rankPolicyLists, policyListService, redisService);

        //获取推荐内容
        List<VOPolicyList> rePolicyList = new ArrayList<>();
        if(token!=null&&!token.equals("")) {
            ServerResponse<List<VOPolicyList>> listServerResponse = recommendedPolicy(token);
            rePolicyList=listServerResponse.getData();
        }
        ServerResponse<IPage<VOPolicyList>> iPageServerResponse =
                allPolicyList(token, current, size, null, null);
        IPage<VOPolicyList> allPolicyListPage = iPageServerResponse.getData();


        voPolicyPage.setAllPolicyList(allPolicyListPage);
        voPolicyPage.setRankPolicyLists(rankPolicyLists);
        voPolicyPage.setRePolicyList(rePolicyList);
        voPolicyPage.setResourceList(resourceList);
        return ServerResponse.createSuccessResponse("请求成功",voPolicyPage);
    }

    @ApiOperation("获取所有政策list的接口")
    @PostMapping("/allpolicylist")//政策主页中用于筛选民族政策的信息，或者排序的信息
    private ServerResponse<IPage<VOPolicyList>> allPolicyList(@RequestHeader(value = "token", required = false) String token
            ,@RequestParam(value = "current") int current
            ,@RequestParam(value = "size") int size
            ,@RequestParam(value = "nationName", required = false)String nationName
            ,@RequestParam(value = "orderType", required = false)Integer orderType//如果为1，那么就按照时间升序排序
    ){
        QueryWrapper<Policy> queryWrapper=new QueryWrapper<>();
        if(nationName!=null&&!nationName.equals("")){
            queryWrapper.eq("nation_name",nationName);
            queryWrapper= queryWrapper.or();
            queryWrapper.eq("nation_name","暂未确定");
        }
        if(orderType!=null){
            if(orderType==1){
                queryWrapper.orderByAsc("publish_time");
            }else{
                queryWrapper.orderByDesc("publish_time");
            }
        }
        //获取所有政策
        IPage<VOPolicyList> allPolicyListPage=new Page<>(current,size);//所有政策
        IPage<Policy> iPage=new Page<Policy>(current,size);
        IPage<Policy> policyIPage=policyListService.page(iPage,queryWrapper);
        allPolicyListPage.setPages(policyIPage.getPages());
        allPolicyListPage.setTotal(policyIPage.getTotal());
        List<Policy> records = policyIPage.getRecords();
        List<VOPolicyList> voPolicyLists=new ArrayList<>();
        records.forEach(policy -> {
            VOPolicyList voPolicyList=new VOPolicyList();
            DataChanges.fromPolicyToVOPolicyList(policy,voPolicyList);
            voPolicyLists.add(voPolicyList);
        });
        allPolicyListPage.setRecords(voPolicyLists);
        return ServerResponse.createSuccessResponse("请求成功",allPolicyListPage);
    }
    @ApiOperation("获取目标用户推荐内容的接口，再次访问表示刷新推荐内容")
    @PostMapping("/recommendedpolicy")//推荐的内容
    private ServerResponse<List<VOPolicyList>> recommendedPolicy(@RequestHeader(value = "token") String token){

        List<VOPolicyList> rePolicy =new ArrayList<>();

        if(token!=null&&!token.equals("")) {
            String uid=JwtTokenUtil.getUserId(token,audience);
            rePolicy= recommendedTools.recommendedPolicy(uid);
            return ServerResponse.createSuccessResponse("请求成功",rePolicy);
        }else{//未登录无法获得推荐
            return ServerResponse.createErrorsResponse(ResultType.UNLOGINERROR);

        }
    }

    @ApiOperation("不感兴趣，更新用户兴趣矩阵")
    @PostMapping("/dislikepolicy")//不感兴趣
    private ServerResponse<String> dislikePolicy(@RequestHeader(value = "token") String token,
                                                 @RequestParam(value = "id")String id){

        return ServerResponse.createSuccessResponse("true");
    }
}
